var express = require('express');
var router = express.Router();
const moment = require('moment')
const accountModel = require('../models/accountModel')
let checkLoginMiddleware = (req, res, next) => {
    if (!req.session.username) {
        return res.redirect('/login')
    }
    next()
}
router.get('/', (req, res) => {
    res.redirect('/account')
})
router.get('/account', checkLoginMiddleware, async function (req, res, next) {
    // let accounts  = db.get('accounts').value()
    // console.log(accounts)
    try {
        const p = await accountModel.find().sort({time: -1})
        // res.send('成功')
        res.render('index', {accounts: p, moment: moment});
    } catch (error) {
        res.status(500)
        console.log(error)
    }

});
router.get('/account/create', checkLoginMiddleware, function (req, res, next) {
    // res.render('index', { title: 'Express' });
    res.render('create');
});
router.get('/account/:id', checkLoginMiddleware, async function (req, res, next) {
    let id = req.params.id
    // db.get('accounts').remove({id:id}).write()
    try {
        const p = await accountModel.deleteOne({_id: id})
        console.log(p)

        res.render('success', {msg: '删除成功', url: '/account'});
    } catch (error) {
        res.status(500)
        res.render('删除失败')
    }

});
router.post('/account', checkLoginMiddleware, async function (req, res, next) {
    // res.render('index', { title: 'Express' });
    // let id = short.generate()
    // console.log(req.body)
    // db.get('accounts').push({id:id,...req.body}).write()
    // console.log(moment('2022-01-03').toDate())
    // console.log(req.body)
    try {
        const p = await accountModel.create({
            ...req.body,
            time: moment(`${req.body.time}`).toDate()
        })
        res.render('success', {msg: '添加成功', url: '/account'});
    } catch (error) {
        res.status(500).send('插入失败')
        console.log(error)
    }

});
module.exports = router;
